package com.leilei.personal;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/fileUpload")
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public FileUpload() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
		IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String uploadFileName = "";
		if (isMultipart) {
			// 创建磁盘工厂，利用构造器实现内存数据储存量和临时储存路径
			DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("D:\\Temp"));
			// 设置最多只允许在内存中存储的数据,单位:字节
			// factory.setSizeThreshold(4096);
			// 设置文件临时存储路径
			// factory.setRepository(new File("D:\\Temp"));
			// 产生一新的文件上传处理程式
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置路径、文件名的字符集
			upload.setHeaderEncoding("UTF-8");
			// 设置允许用户上传文件大小,单位:字节
			upload.setSizeMax(1024 * 1024 * 100);
			// 解析请求，开始读取数据
			// Iterator<FileItem> iter = (Iterator<FileItem>) upload.getItemIterator(request);
			// 得到所有的表单域，它们目前都被当作FileItem
			List<FileItem> fileItems = null;
			try {
				fileItems = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 依次处理请求
			Iterator<FileItem> iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					// 如果item是正常的表单域
					String name = item.getFieldName();
					String value = item.getString("UTF-8");
					System.out.println("表单域名为:" + name + "表单域值为:" + value);
				} else {
					// 如果item是文件上传表单域
					// 获得文件名及路径
					String fileName = item.getName();
					if (fileName != null) {
						// 如果文件存在则上传
						File fullFile = new File(item.getName());
						if (fullFile.exists()) {
							uploadFileName = fullFile.getName();
							File fileOnServer = new File("D:\\Temp\\" + fullFile.getName());
							try {
								item.write(fileOnServer);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				item.delete();
			}
			System.out.println("File:" + uploadFileName + "Upload successfully!");
			 PrintWriter out = response.getWriter();
			 out.print("<%@page contentType='text/html' pageEncoding='UTF-8'%>");							 
			 out.print("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
			 out.print("<html>");
			 out.print("<head>");
			 out.print("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
			 out.print("</head>");
			 out.print("<body>");
			 out.print("<h1>File  " + uploadFileName + "  Success!</h1>");
			 out.print("</body>");
			 out.print("</html>");
		}
	}

}
